package com.py.credit.service.impl;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.py.credit.service.XypjRemoteBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.dao.GatewayDeclarationInformationDao;
import com.py.credit.entity.GatewayUserEntity;
import com.py.credit.service.GatewayDeclarationInformationService;
import com.py.credit.service.IndexService;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.rest.support.RestServiceResult;

/**
 * 信用评价前台网站信用申报ServiceImpl
 */
@Service
public class GatewayDeclarationInformationServiceImpl implements GatewayDeclarationInformationService {

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@Autowired
	private GatewayDeclarationInformationDao gatewayDeclarationInformationDao;

	@Autowired
	private IndexService indexService;

	@Override
	public List<LinkedHashMap> selectDeclarationInformationList(String tybm, int rootId) {

		// 查询信用申报的表
		String[] relateSourceId = gatewayDeclarationInformationDao.selectRelateSourceId(rootId).split(",");
		List<LinkedHashMap> tableList = gatewayDeclarationInformationDao.selectTableList(Arrays.asList(relateSourceId));

		for (LinkedHashMap map : tableList) {
			map.put("totalCount",
					gatewayDeclarationInformationDao.selectTableValueCount(tybm, (String) map.get("resource_id")));
			map.put("tableFiled",
					gatewayDeclarationInformationDao.selectTableFiledList((String) map.get("resource_id")));
		}

		return tableList;
	}

	@Override
	public List<LinkedHashMap> selectListForPage(String tybm, String tableName, Page page) {
		return gatewayDeclarationInformationDao.selectDeclarationInformationListForPage(tybm,
				gatewayDeclarationInformationDao.selectTableFieldSql(tableName), tableName, page);
	}

	@Override
	public LinkedHashMap selectInfo(String tableName, String id) {
		return gatewayDeclarationInformationDao.selectDeclarationInformationInfo(
				gatewayDeclarationInformationDao.selectTableFieldSql(tableName), tableName, id);
	}

	@Override
	public RestServiceResult addInfo(GatewayUserEntity gatewayUserEntity, String tableName, String data) {
		StringBuffer filedBuffer = new StringBuffer();
		StringBuffer valueBuffer = new StringBuffer();

		Map<String, Object> info = new HashMap<String, Object>();

		// 解析json字段,拼接字段和值
		JSONArray filedList = JSON.parseArray(data);
		for (int i = 0; i < filedList.size(); i++) {
			JSONObject filedMap = filedList.getJSONObject(i);

			// 校验一下字段
			List<Map<String, String>> columnRuleList = this
					.selectColumnRuleList(Arrays.asList(filedMap.getString("roleId").split(",")));
			for (Map<String, String> map : columnRuleList) {
				if (!this.checkRule(map.get("rule_package"), map.get("rule_method"), filedMap.getString("value"), "")) {
					info.put("flag", "N");
					info.put("msg", filedMap.getString("columnCn") + ":" + map.get("rule_prompt"));
					return new RestServiceResult(info);
				}
			}

			// 拼接sql
			filedBuffer.append(filedMap.getString("columnEn") + ",");
			if (null == filedMap.getString("value") || "".equals(filedMap.getString("value"))) {
				valueBuffer.append("'0'" + ",");
			} else {
				valueBuffer.append("'" + filedMap.getString("value") + "'" + ",");
			}
		}

		// 拼接其他属性值
		filedBuffer.append("ID,A000001,A000002,tybm,pg_id");
		valueBuffer.append("'" + UuidUtil.INSTANCE.getUUid() + "'" + ",")
				.append("'" + gatewayUserEntity.getZtmc() + "'" + ",")
				.append("'" + gatewayUserEntity.getBm() + "'" + ",")
				.append("'" + gatewayUserEntity.getTybm() + "'" + ",").append("'" + gatewayUserEntity.getId() + "'");

		// 拼接sql
		StringBuffer sql = new StringBuffer();
		sql.append(" insert into " + tableName).append(" (" + filedBuffer.toString() + ") ")
				.append(" values (" + valueBuffer.toString() + ") ");

		try {
			gatewayDeclarationInformationDao.addInfo(sql.toString());
			indexService.saveFinanceData(String.valueOf(gatewayUserEntity.getId()));
			info.put("flag", "Y");
			info.put("msg", "操作成功");
		} catch (Exception e) {
			info.put("flag", "Y");
			info.put("msg", "操作失败");
		}

		return new RestServiceResult(info);
	}

	@Override
	public RestServiceResult modifyInfo(String id, String tableName, String data) {
		StringBuffer buffer = new StringBuffer();

		Map<String, Object> info = new HashMap<String, Object>();

		// 解析json字段,拼接字段和值
		JSONArray filedList = JSON.parseArray(data);
		for (int i = 0; i < filedList.size(); i++) {
			JSONObject filedMap = filedList.getJSONObject(i);

			// 校验一下字段
			List<Map<String, String>> columnRuleList = this
					.selectColumnRuleList(Arrays.asList(filedMap.getString("roleId").split(",")));
			for (Map<String, String> map : columnRuleList) {
				if (!this.checkRule(map.get("rule_package"), map.get("rule_method"), filedMap.getString("value"), "")) {
					info.put("flag", "N");
					info.put("msg", filedMap.getString("columnCn") + ":" + map.get("rule_prompt"));
					return new RestServiceResult(info);
				}
			}

			// 拼接sql
			buffer.append(filedMap.getString("columnEn"));
			if (null == filedMap.getString("value") || "".equals(filedMap.getString("value"))) {
				buffer.append("='0',");
			} else {
				buffer.append("='" + filedMap.getString("value") + "'" + ",");
			}
		}

		// 删除最后一个逗号
		buffer.deleteCharAt(buffer.length() - 1);

		// 拼接sql
		StringBuffer sql = new StringBuffer();
		sql.append(" update " + tableName).append(" set " + buffer.toString() + " ");

		try {
			gatewayDeclarationInformationDao.modifyInfo(sql.toString(), id);
			String pgId = gatewayDeclarationInformationDao.selectPgIdById(tableName, id);
			info.put("flag", "Y");
			info.put("msg", "操作成功");
			indexService.saveFinanceData(pgId);
		} catch (Exception e) {
			info.put("flag", "Y");
			info.put("msg", "操作失败");
		}

		return new RestServiceResult(info);
	}

	@Override
	public void delInfo(String id, String tableName) {
		gatewayDeclarationInformationDao.delInfo(id, tableName);
	}

	@Override
	public List<LinkedHashMap> selectTableTitleList(String tableName) {
		return gatewayDeclarationInformationDao.selectTableTitleList(tableName);
	}

	@Override
	public boolean checkRule(String packageName, String methodName, String data, String extend) {
		Class<?> c = null;
		Method m = null;
		boolean validate = false;

		try {
			c = Class.forName(packageName);
			m = c.getMethod(methodName, String.class, String.class);
			validate = (boolean) m.invoke(c.newInstance(), data, extend);
		} catch (Exception e) {
			return false;
		}

		return validate;
	}

	@Override
	public List<Map<String, String>> selectColumnRuleList(List<String> ids) {
		return gatewayDeclarationInformationDao.selectColumnRuleList(ids);
	}
}